package com.unibert.podcastq;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.jsoup.Jsoup;
import org.jsoup.select.Elements;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.Shader.TileMode;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager.WifiLock;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.unibert.items.Elemento;
import com.unibert.items.ElementoComentario;
import com.unibert.items.item;
import com.unibert.podcastq.BD.BD;

public class MainActivity extends Activity {
	
    final int HELLO_ID = 1;

	@Override
	public boolean isFinishing() {
		// TODO Auto-generated method stub
		return super.isFinishing();
	}


	@SuppressWarnings("deprecation")
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		 String ns = Context.NOTIFICATION_SERVICE;
         NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

         int icon = R.drawable.attchment;        // icon from resources
         CharSequence tickerText =  " Program Running...";              // ticker-text
         long when = System.currentTimeMillis();         // notification time
         Context context = getApplicationContext();      // application Context
         CharSequence contentTitle = "EL QUE TE FOCA";  // expanded message title
         CharSequence contentText = " Program Running...";      // expanded message text

         Intent notificationIntent = new Intent(this, MainActivity.class);
         PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

         // the next two lines initialize the Notification, using the configurations above
         Notification notification = new Notification(icon, tickerText, when);
         notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

        notification.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;   
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        mNotificationManager.notify(HELLO_ID, notification);
	}


	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		String ns = Context.NOTIFICATION_SERVICE;
	    NotificationManager nMgr = (NotificationManager) this.getSystemService(ns);
	    nMgr.cancel(HELLO_ID);
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}


	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}


	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}
	
	
	WifiLock wifiLock;
	public class MyService extends Service implements MediaPlayer.OnPreparedListener {


		/** Called when MediaPlayer is ready */
		@SuppressWarnings("deprecation")
		public void onPrepared(MediaPlayer player) {
			preparado=true;
			total.setText(ElementoActual.getDuration());
			playAudio();
//			mediaPlayer.setWakeMode(MainActivity.this, PowerManager.PARTIAL_WAKE_LOCK);
//
//			String songName = ElementoActual.getTitles();
//			PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0,
//					new Intent(MainActivity.this, MainActivity.class),
//					0);
//			
//			Notification notification = new Notification();
//			notification.tickerText = "HOLA";
//			notification.icon = R.drawable.btn_info;
//			notification.flags |= Notification.FLAG_ONGOING_EVENT;
//			notification.setLatestEventInfo(MainActivity.this, "MusicPlayerSample",
//					"Playing: " + songName, pi);
//			final int myID = 121235234;
//			startForeground(myID, notification);
			
		}
		public int onStartCommand(Intent intent, int flags, int startId) {
			return startId;
	  
	        
	    }

		
		public void startnotificacion(){
			
		}
		public void stopnotificacion(){
			stopForeground(true);
			wifiLock.release();
		}

		@Override
		public IBinder onBind(Intent intent) {
			// TODO Auto-generated method stub
			return null;
		}
	}

	@Override
	public void onBackPressed() { 
		AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
		builder.setMessage("Seguro que quieres salir?")
		.setCancelable(false)
		.setPositiveButton("SI", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				String ns = Context.NOTIFICATION_SERVICE;
			    NotificationManager nMgr = (NotificationManager) MainActivity.this.getSystemService(ns);
			    nMgr.cancel(HELLO_ID);
				System.exit(1);
			}
		})
		.setNegativeButton("NO", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
			}
		});
		AlertDialog alert = builder.create();
		alert.show();

	}         


	private boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager 
		= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
		return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}

	private static class AsyncTaskUpdateFoto extends AsyncTask<String, String, String> {
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			fotito.setImageBitmap(mapaImagen);
		}
		Bitmap mapaImagen;
		@Override
		protected String doInBackground(String... params) {
			mapaImagen = getBitmapFromURL(ElementoActual.getFoto(), 1, ElementoActual.getId());
			return null;

		}


	}
	private  class DescargaSong extends AsyncTask<String, Integer, String> {
		ProgressDialog mProgressDialog;
		String titulo;

		// instantiate it within the onCreate method

		@Override
		protected String doInBackground(String... params) {
			try{
				String idactual = ElementoActual.getId();

				URL url = new URL(ElementoActual.getURL());
				URLConnection conexion = url.openConnection();
				conexion.connect();
				// this will be useful so that you can show a tipical 0-100% progress bar
				int lenghtOfFile = conexion.getContentLength();
				String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
				File wallpaperDirectory = new File(extStorageDirectory+"/Qpod/");
				// have the object build the directory structure, if needed.
				wallpaperDirectory.mkdirs();
				extStorageDirectory += "/Qpod";
				InputStream input = new BufferedInputStream(url.openStream());
				File file = new File(extStorageDirectory, ElementoActual.getTitles()+".mp3");
				OutputStream output = new FileOutputStream(file);

				byte data[] = new byte[1024];

				long total = 0;

				int count;
				while ((count = input.read(data)) != -1) {
					total += count;
					// publishing the progress....
					publishProgress((int)(total*100/lenghtOfFile));
					output.write(data, 0, count);
				}

				output.flush();
				output.close();
				input.close();

				SQLiteDatabase song2file = basededatoshelper.getWritableDatabase();
				song2file.execSQL("UPDATE PODCAST SET url='"+extStorageDirectory+"/"+ElementoActual.getTitles()+".mp3', " +
						"descargado=1 where id="+idactual);
			}catch(Exception e){
				e.printStackTrace();
				return "KO";
			}
			return "OK";

		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			mProgressDialog.dismiss();
			if(result.equalsIgnoreCase("OK"))
				Toast.makeText(MainActivity.this, titulo+" DESCARGADO", Toast.LENGTH_SHORT).show();
			else
				Toast.makeText(MainActivity.this, "DESCARGA "+ titulo +" FALLIDA", Toast.LENGTH_SHORT).show();


		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			titulo = ElementoActual.getTitles();
			mProgressDialog = new ProgressDialog(MainActivity.this);
			mProgressDialog.setMessage("Descargando Podcast :\n"+ElementoActual.getTitles());
			mProgressDialog.setIndeterminate(false);
			mProgressDialog.setCancelable(true);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgressDialog.show();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
			mProgressDialog.setProgress(values[0]);
		}

	}

	static boolean descargado;

	static ArrayList<item> items = new ArrayList<item>();
	private static ImageButton btn_play;
	private static ImageButton btn_btn;
	public static ArrayList<ElementoComentario> Lista = null;
	private static ImageButton btn_cmt;
	private static ScrollView pantalla;

	private static Bitmap myBitmap;
	private static ImageView fotito;
	private SeekBar seekBar;
	public static MediaPlayer mediaPlayer;
	public static int lengthOfAudio;
	public static String URL;
	private final Handler handler = new Handler();
	public static Elemento ElementoActual;
	private static boolean preparado = false;

	private static final int SWIPE_MIN_DISTANCE = 120;
	private static final int SWIPE_MAX_OFF_PATH = 250;
	private static final int SWIPE_THRESHOLD_VELOCITY = 200;
	private GestureDetector gestureDetector;
	private TextView actual;
	private TextView total;
	private ImageButton botonListaDescargados;
	private ImageButton descargar;
	View.OnTouchListener gestureListener;
	private static int numeroLista;
	private static MyService servicio;

	static BD basededatoshelper;


	private float downXValue;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == 1 || requestCode ==2) {
			descargado = true;


			if(resultCode == RESULT_OK && !ElementoActual.getId().equalsIgnoreCase(data.getStringExtra("pos"))){

				//				ComentariosDescargados=false;

				//				new AsyncTaskUpdateUrlcomments().execute(null);
				if(Lista!=null)Lista.clear();
				Lista=null;
				SQLiteDatabase db;
				String idmax="0";
				db = basededatoshelper.getReadableDatabase();
				String[] arg = {data.getStringExtra("pos")};
				Cursor cursor = db.query("PODCAST",null , "id=?" , arg , null, null , null , null);
				cursor.moveToFirst();
				while(!cursor.isAfterLast()){
					idmax = ""+cursor.getInt(0);
					ElementoActual.setId(idmax);
					ElementoActual.setTitles(cursor.getString(1));
					ElementoActual.setAuthor(cursor.getString(2));
					ElementoActual.setSummary(cursor.getString(3));
					ElementoActual.setPubdate(cursor.getString(4));
					ElementoActual.setDuration(cursor.getString(5));
					ElementoActual.setURL(cursor.getString(6));
					ElementoActual.setFoto(cursor.getString(7));
					ElementoActual.setDescargado(cursor.getString(8));
					ElementoActual.setLink(cursor.getString(10));
					cursor.moveToNext();
				}
				cursor.close();
				db.close();
				String INFO = ElementoActual.getTitles();
				URL = ElementoActual.getURL();
				TextView tv = (TextView) findViewById(R.id.datosPodcast);
				TextView resumen = (TextView) findViewById(R.id.resumen);
				resumen.setText(ElementoActual.getSummary());
				tv.setText(INFO);
				actual.setText("00:00");
				total.setText("00:00");
				seekBar.setSecondaryProgress(0);
				if(ElementoActual.getDescargado().equalsIgnoreCase("1")){
					descargar.setImageBitmap(null);
					descargar.setClickable(false);
				}else{
					descargar.setImageResource(R.drawable.attchment);
					descargar.setClickable(true);
				}
				new AsyncTaskUpdateFoto().execute();

				try {

					btn_play.setImageResource(R.drawable.btn_play);
					mediaPlayer.reset();
					mediaPlayer.setDataSource(URL);	
					preparado = false;
					mediaPlayer.setOnPreparedListener(servicio);
					mediaPlayer.prepareAsync();
					seekBar.setProgress(0);
					seekBar.setSecondaryProgress(0);

				} catch (Exception e) {
					Log.e("Error", e.getMessage());
				}

			}
		}
	}


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		servicio = new MyService();


		setContentView(R.layout.reproductor_layout);
		descargado = false;
		basededatoshelper = new BD(this,"QCU", null, 11);
		if(isNetworkAvailable()){
			AsyncTaskUpdateUrl up = new AsyncTaskUpdateUrl();
			up.execute("");
		}
		else{
			Toast.makeText(this, "No hay conexion a internet. Funcionalidad limitada", Toast.LENGTH_SHORT).show();
		}
		if(isNetworkAvailable()){
			gestureDetector = new GestureDetector(new MyGestureDetector());
			gestureListener = new View.OnTouchListener() {
				public boolean onTouch(View v, MotionEvent event) {
					return gestureDetector.onTouchEvent(event);
				}
			};


			descargar = (ImageButton) findViewById(R.id.descarga);
			descargar.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					new DescargaSong().execute();

				}
			});
		}
		pantalla = (ScrollView) findViewById(R.id.scrollView1);
		actual = (TextView) findViewById(R.id.songCurrentDurationLabel);
		total = (TextView) findViewById(R.id.songTotalDurationLabel);
		if(isNetworkAvailable()){
			pantalla.setOnTouchListener(gestureListener);
		}
		ImageButton bt = (ImageButton) findViewById(R.id.botonLista);
		botonListaDescargados = (ImageButton) findViewById(R.id.botonListaDescargados);
		botonListaDescargados.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if(numeroLista==1){
					descargado=false;

				}
				numeroLista=2;
				Intent listadescargados = new Intent(MainActivity.this, ListActivity.class);
				listadescargados.putExtra("DESCARGADOS", true);
				startActivityForResult(listadescargados,2);

			}
		});


		if(isNetworkAvailable()){
			bt.setOnClickListener(new View.OnClickListener(){ 
				@Override
				public void onClick(View v) 
				{ 
					if(numeroLista==2){
						descargado=false;
					}

					numeroLista=1;
					mediaPlayer.reset();
					Intent intento = new Intent(MainActivity.this, ListActivity.class);
					intento.putExtra("DESCARGADOS", false);
					startActivityForResult(intento,1); 
				}});
		}

		if(isNetworkAvailable()){
			btn_btn = (ImageButton)findViewById(R.id.imageView1);
			btn_cmt = (ImageButton)findViewById(R.id.imageView2);
			btn_btn.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					Intent botons = new Intent(MainActivity.this,Botones.class);
					botons.putExtra("LINK", ElementoActual.getLink());
					startActivity(botons);
				}
			});

			btn_cmt.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent elementito = new Intent(MainActivity.this,Comments.class);
					elementito.putExtra("id", ElementoActual.getId());
					startActivity(elementito);
				}
			});
		}

		fotito = (ImageView) findViewById(R.id.fotoportada);

		btn_play = (ImageButton)findViewById(R.id.btn_play);
		btn_play.setOnClickListener(new View.OnClickListener(){ 
			public void onClick(View v) 
			{  // check for already playing
				if(mediaPlayer.isPlaying()){
					if(mediaPlayer!=null){
						pauseAudio();
						// Changing button image to play button
						btn_play.setImageResource(R.drawable.btn_play);
					}
				}else{
					// Resume song
					if(mediaPlayer!=null&&preparado){
						playAudio();
						// Changing button image to pause button
						btn_play.setImageResource(R.drawable.btn_pause);
					}
					else{
						Toast.makeText(getApplicationContext(), "El podcast se esta cargando...\nESPERA xfavor!!!", Toast.LENGTH_SHORT).show();
					}
				}
			} 
		}); 

		mediaPlayer = new MediaPlayer();
		seekBar = (SeekBar)findViewById(R.id.seekBar);
		seekBar.setOnSeekBarChangeListener( new OnSeekBarChangeListener() {

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub

				if(fromUser){
					int secondaryPosition = seekBar.getSecondaryProgress();
					if (progress > secondaryPosition&&"0".equalsIgnoreCase(ElementoActual.getDescargado()))
						seekBar.setProgress(secondaryPosition);
					else{
						mediaPlayer.seekTo((mediaPlayer.getDuration() / 100) * progress );
						int aux = mediaPlayer.getCurrentPosition();
						String minutos = (int)((int)aux/1000)/60+"";
						String segundos = (int)((int)aux/1000)%60+"";
						if(minutos.length()==1)minutos = "0"+minutos;
						if(segundos.length()==1)segundos = "0"+segundos;
						actual.setText(minutos+":"+segundos);


					}
				}else{

				}

			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

		});




		mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener(){ 
			@Override
			public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
				seekBar.setSecondaryProgress(percent);
			}
		}); 


		mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){ 
			@Override
			public void onCompletion(MediaPlayer mp) {
				btn_play.setEnabled(true);
//				wifiLock.release();
			}
		}); 
	}



	private void updateSeekProgress() {
		if (mediaPlayer.isPlaying()) {
			seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / mediaPlayer.getDuration()) * 100));
			int aux = mediaPlayer.getCurrentPosition();
			String minutos = (int)((int)aux/1000)/60+"";
			String segundos = (int)((int)aux/1000)%60+"";
			if(minutos.length()==1)minutos = "0"+minutos;
			if(segundos.length()==1)segundos = "0"+segundos;
			actual.setText(minutos+":"+segundos);
			handler.postDelayed(new Runnable() {	

				@Override
				public void run() {
					updateSeekProgress();					
				}
			}, 1000);
		}
	}

	private void stopAudio() {
		mediaPlayer.stop();
		seekBar.setProgress(0);
	}

	private void pauseAudio() {
		mediaPlayer.pause();
	}

	private void playAudio() {
		btn_play.setImageResource(R.drawable.btn_pause);
		mediaPlayer.start();
		updateSeekProgress();
	}


	private class AsyncTaskUpdateUrl extends AsyncTask<String, String, String> {

		ProgressDialog dialog;
		int fotodescargada;
		String INFO;
		private String update_url() {

			try {

				ElementoActual = new Elemento();
				SQLiteDatabase db;
				String idmax="0";
				db = basededatoshelper.getReadableDatabase();
				Cursor cursor = db.query("PODCAST",null , null , null , null, null , "id DESC" , "1");
				cursor.moveToFirst();
				while(!cursor.isAfterLast()){
					idmax = ""+cursor.getInt(0);
					ElementoActual.setId(idmax);
					ElementoActual.setTitles(cursor.getString(1));
					ElementoActual.setAuthor(cursor.getString(2));
					ElementoActual.setSummary(cursor.getString(3));
					ElementoActual.setPubdate(cursor.getString(4));
					ElementoActual.setDuration(cursor.getString(5));
					ElementoActual.setURL(cursor.getString(6));
					ElementoActual.setFoto(cursor.getString(7));
					ElementoActual.setDescargado(cursor.getString(8));
					fotodescargada = cursor.getInt(9);
					ElementoActual.setLink(cursor.getString(10));
					cursor.moveToNext();
				}

				cursor.close();
				db.close();
				db = basededatoshelper.getWritableDatabase();
				boolean primero = true;
				//				if(false){
				java.net.URL url = new java.net.URL("http://cristianosuniversitarios.org/feed/podqast");
				org.jsoup.nodes.Document doc = Jsoup.parse(url,100000);
				Elements item = doc.getElementsByTag("item");
				for (org.jsoup.nodes.Element tablaelm : item) {
					String id = tablaelm.getElementsByTag("guid").text().split("p=")[1];					
					String titulo = tablaelm.getElementsByTag("title").text();
					String web = tablaelm.getElementsByTag("comments").text().split("#")[0];
					String fecha = tablaelm.getElementsByTag("pubdate").text();
					String autor = tablaelm.getElementsByTag("itunes:author").text();
					String resumen = tablaelm.getElementsByTag("itunes:subtitle").text().split("-")[0];
					String duracion = tablaelm.getElementsByTag("itunes:duration").text();
					String foto = tablaelm.getElementsByTag("rawvoice:poster").attr("url").split(".jpg")[0]+"-150x150.jpg";
					String urlaudio = tablaelm.getElementsByTag("enclosure").attr("url");					
					if(primero&&Integer.parseInt(id)>Integer.parseInt(idmax)){
						ElementoActual.setId(id);
						ElementoActual.setTitles(titulo);
						ElementoActual.setAuthor(autor);
						ElementoActual.setSummary(resumen);
						ElementoActual.setPubdate(fecha);
						ElementoActual.setDuration(duracion);
						ElementoActual.setURL(urlaudio);
						ElementoActual.setFoto(foto);
						ElementoActual.setDescargado("0");
						ElementoActual.setLink(web);

						fotodescargada = 0;
						primero = false;
					}

					if(Integer.parseInt(idmax)>=Integer.parseInt(id)){
						myBitmap = getBitmapFromURL(ElementoActual.getFoto(), fotodescargada, ElementoActual.getId());
						db.close();
						return "OK";
					}

					db.execSQL("INSERT INTO PODCAST VALUES (" +
							"" +id+", "+
							"'" +titulo+"', "+
							"'" +autor+"', "+
							"'" +resumen+"', "+
							"'" +fecha+"', "+
							"'" +duracion+"', "+
							"'" +urlaudio+"', "+
							"'" +foto+"', "+
							"0, 0" +
							", '"+web+"')");//no descargado
					

				}
				//				}
				myBitmap = getBitmapFromURL(ElementoActual.getFoto(), fotodescargada, ElementoActual.getId());
				db.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "OK";


		}


		@Override
		protected void onPreExecute() {
			try {

				dialog = new ProgressDialog(MainActivity.this);
				dialog.setTitle(MainActivity.this.getString(R.string.cargando));
				dialog.setMessage(MainActivity.this.getString(R.string.obtInfoServer));
				dialog.setCancelable(false);
				dialog.show();
			} catch (final Exception e) {
				Log.e("Error", e.getMessage());
			}
		}

		@Override
		protected String doInBackground(String... strings) {
			try {
				return update_url();

			}  catch (final Exception e) {
				Log.e("ERROR", e.getCause().toString());
				return "KO";
			}
		}

		@Override
		protected void onPostExecute(final String result) {
			try {
				dialog.dismiss();
			} catch (Exception e) {
				Log.i("MI_ERROR", e.getCause().toString());
			}
			if(result == "OK"){
				//get position
				//show podcast information
				if(ElementoActual.getDescargado().equalsIgnoreCase("1")){
					descargar.setImageBitmap(null);
					descargar.setClickable(false);
				}
				String INFO = ElementoActual.getTitles();
				URL = ElementoActual.getURL();
				TextView tv = (TextView) findViewById(R.id.datosPodcast);
				tv.setText(INFO);
				TextView resumen = (TextView) findViewById(R.id.resumen);
				resumen.setText(ElementoActual.getSummary());
				ImageView fotito = (ImageView) findViewById(R.id.fotoportada);
				fotito.setImageBitmap(myBitmap);

				//prepare audio
				//				new AsyncTaskUpdateUrlcomments().execute(null);
				try {
					mediaPlayer.reset();
					mediaPlayer.setDataSource(URL);
					preparado = false;
					mediaPlayer.setOnPreparedListener(servicio);
					mediaPlayer.prepareAsync();
				} catch (Exception e) {
					Log.e("Error", e.getMessage());
				}


			}else{
				Toast.makeText(getApplicationContext(),getApplicationContext().getString(R.string.connectionError), Toast.LENGTH_SHORT).show();

			}






		}
	}

	class MyGestureDetector extends SimpleOnGestureListener {
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
			try {
				if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
					return false;
				// right to left swipe
				if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
					//					if(ComentariosDescargados){
					Intent comentarios = new Intent(MainActivity.this,Comments.class);
					comentarios.putExtra("id", ElementoActual.getId());
					startActivity(comentarios);
					//					}

				}  else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
					Intent botons = new Intent(MainActivity.this,Botones.class);
					botons.putExtra("LINK", ElementoActual.getLink());
					startActivity(botons);
				}
			} catch (Exception e) {
				// nothing
			}
			return false;
		}

	}
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (!isNetworkAvailable()||gestureDetector.onTouchEvent(event)){
			if(!isNetworkAvailable())Toast.makeText(this, "No hay conexion a internet disponible. Funcionalidad limitada", Toast.LENGTH_SHORT).show();
			return true;
		}
		else
			return false;
	} 
	public static Bitmap getBitmapFromURL(String src, Integer descargada, String id) {
		try{
			if(descargada==0){
				URL url = new URL(src);
				InputStream input = url.openStream();
				myBitmap = BitmapFactory.decodeStream(input);
				Log.e("Bitmap","returned");
				String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
				OutputStream outStream = null;
				File wallpaperDirectory = new File(extStorageDirectory+"/Qpod/");
				// have the object build the directory structure, if needed.
				wallpaperDirectory.mkdirs();
				extStorageDirectory += "/Qpod";
				File file = new File(extStorageDirectory, id+".QPJPEG");
				outStream = new FileOutputStream(file);
				myBitmap.compress(Bitmap.CompressFormat.JPEG, 80, outStream);
				outStream.flush();
				outStream.close();
				SQLiteDatabase db;
				db = basededatoshelper.getWritableDatabase();
				db.execSQL("UPDATE PODCAST SET fotodescargada='1', foto='"+extStorageDirectory+"/"+id+".QPJPEG' WHERE id ='"+id+"'" );
				db.close();

			}else{
				myBitmap = BitmapFactory.decodeFile(src);
			}
//			return getDropShadow3(myBitmap);
			return myBitmap;

		} catch (Exception e) {
			e.printStackTrace();
			Log.e("Exception",e.getMessage());
			return null;
		}
	}
	private static Bitmap getDropShadow3(Bitmap bitmap) {

		 int w = bitmap.getWidth();
		    int h = bitmap.getHeight();

		    int newW = w - (2 * 2);
		    int newH = h - (2 + 2);

		    Bitmap.Config conf = Bitmap.Config.ARGB_8888;
		    Bitmap bmp = Bitmap.createBitmap(w, h, conf);
		    Bitmap sbmp = Bitmap.createScaledBitmap(bitmap, newW, newH, false);

		    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
		    Canvas c = new Canvas(bmp);

		    // Left
		    int leftMargin = (2 + 7)/2;
		    Shader lshader = new LinearGradient(0, 0, leftMargin, 0, Color.TRANSPARENT, Color.BLACK, TileMode.CLAMP);
		    paint.setShader(lshader);
		    c.drawRect(0, 2, leftMargin, newH, paint); 

		    // Right
		    Shader rshader = new LinearGradient(w - leftMargin, 0, w, 0, Color.BLACK, Color.TRANSPARENT, TileMode.CLAMP);
		    paint.setShader(rshader);
		    c.drawRect(newW, 2, w, newH, paint);

		    // Bottom
		    Shader bshader = new LinearGradient(0, newH, 0, bitmap.getHeight(), Color.BLACK, Color.TRANSPARENT, TileMode.CLAMP);
		    paint.setShader(bshader);
		    c.drawRect(leftMargin -3, newH, newW + leftMargin + 3, bitmap.getHeight(), paint);
		    c.drawBitmap(sbmp, 2, 0, null);

		    return bmp;

	}
}
